package com.ngkj.zmfptback.sys.handler;

import com.ngkj.zmfptback.sys.bean.RoleEntity;
import com.ngkj.zmfptback.sys.bean.UserEntity;
import com.ngkj.zmfptback.sys.config.JwtConfig;
import com.ngkj.zmfptback.sys.service.read.UserReadService;
import com.ngkj.zmfptback.sys.util.JwtTokenUtil;
import com.ngkj.zmfptback.sys.util.ResultUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 登录成功自定义处理器
 * @author ChenHN
 * @since 2021/12/1 creation
 **/
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserReadService userReadService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String username = (String) authentication.getPrincipal();
        UserEntity userEntity = userReadService.getUserByUsername(username);
        //获取角色权限，注入用户
        List<RoleEntity> roleByUserId = userReadService.getRoleByUserId(userEntity.getId());
        Set<GrantedAuthority> authorities = new HashSet<>();
        roleByUserId.forEach(item ->{
            authorities.add(new SimpleGrantedAuthority("ROLE_"+item.getRoleCode()));
        });
        userEntity.setAuthorities(authorities);
        String token = JwtTokenUtil.createAccessToken(userEntity);
        token = JwtConfig.tokenPrefix + token;
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message","登录成功");
        map.put("token",token);
        ResultUtil.responseJson(httpServletResponse, map);
    }
}
